#include "ticketbooking.h"
#include "ui_ticketbooking.h"
#include <QDebug>
#include <QThread>
#include <QThreadPool>
#include <functional>
#include <QtConcurrent/QtConcurrent>
#include <QMetaObject>

TicketBooking::TicketBooking(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TicketBooking)
{
    ui->setupUi(this);
}

TicketBooking::~TicketBooking()
{
    delete ui;
}


void TicketBooking::run()
{
    int id = m_number++;
    while(!m_isAbort)
    {
        if(m_res > 0)
        {
            m_res--;
            //错误做法xxx 在子线程中直接操作主线程UI界面
            //ui->textBrowser->insertPlainText(QString("%1").arg(m_res));

            //推荐做法
            auto msg = QString("你的小助手%1正在抢票中~\n").arg(id);
            QMetaObject::invokeMethod(ui->textBrowser, "insertPlainText", Q_ARG(QString, msg));
        }
        qDebug() << "res " << m_res;
        if(!m_isVip) {
            QThread::msleep(1000);    //模拟延迟
        } else {
            QThread::msleep(500);
        }
    }
    qDebug() << "线程 " << QThread::currentThreadId() << " 结束了.";
}

void TicketBooking::on_startBtn_clicked()
{
    qDebug() << "start button clicked...";
    //开始抢票
    if(!m_isTicketGrabbing)
    {
        m_isTicketGrabbing = true;
        ui->startBtn->setText(QString("停止抢票"));
        m_isAbort = false;
//        QThreadPool::globalInstance()->start(std::bind(&TicketBooking::run, this));

        m_number = 1;
        for(int i = 0; i < 2; ++i) {
            //线程池
            QtConcurrent::run(this, &TicketBooking::run);
        }

        m_elapsedTimer.start();

    //停止抢票
    }else{
        m_isTicketGrabbing = false;
        ui->startBtn->setText(QString("开始抢票"));
        m_isAbort = true;
    }
}

void TicketBooking::on_vipBtn_clicked()
{
    qDebug() << "vip button clicked...";
    m_isVip = true;
}


//textBrowser的TextChanged事件
void TicketBooking::on_textBrowser_textChanged()
{
    //右边下拉框一直跟踪光标展示
    ui->textBrowser->ensureCursorVisible();

    qint64  t = m_elapsedTimer.elapsed() / 1000;
    ui->displayTimeLabel->setText(QString("小助手们已经抢票%1小时%2分%3秒").arg(t/60/60)
                                  .arg(t/60%60)
                                  .arg(t%60));
}
